package com.tju.resource.tool.img;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

/**
 * @Author CLS
 * @Date 2022/4/20 13:18
 */
public class ImgUtils {
    /**
     * http地址图片转输入流
     *
     * @param fileUrl
     * @return
     * @throws Exception
     */
    public static InputStream imgIs(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        return conn.getInputStream();
    }

    /**
     * 压缩图片
     *
     * @param file
     * @return
     * @throws MalformedURLException
     */
    public static int[] lengthWidth(File file) throws IOException {
        BufferedImage imageIcon = ImageIO.read(file);
        int iconWidth = imageIcon.getWidth();
        int iconHeight = imageIcon.getHeight();
        return new int[]{(int) (iconWidth - (iconWidth * 0.3)), (int) (iconHeight - (iconHeight * 0.3))};
    }
}
